import { Component, OnInit, Input, OnChanges, SimpleChanges, EventEmitter, Output } from '@angular/core';
import { CommunicateService } from '../communicate.service';

@Component({
  selector: 'app-son',
  templateUrl: './son.component.html',
  styleUrls: ['./son.component.less']
})
export class SonComponent implements OnInit, OnChanges {


  private _str = '';

  logs: Array<string> = [];

  get str(): string {
    return this._str;
  }

  @Input()
  set str(val: string) {
    this._str = val.trim() ? val : '无名氏';
  }



  // 自定义事件（用户子组件通知父组件）
  @Output()
  changeEV: EventEmitter<string> = new EventEmitter<string>();

  constructor(private cs: CommunicateService) { }

  ngOnInit() {
  }


  ngOnChanges(changes: SimpleChanges): void {

    const chg = changes.str;

    if (chg) {
      let log = '';
      const currentValue = chg.currentValue;
      const prevValue = chg.previousValue;

      if (chg.isFirstChange()) {
        log = `初始化str为${currentValue}`;
      } else {
        log = `str由${prevValue}变为${currentValue}`;
      }

      this.logs.push(log);
    }
  }

  changeName(): void {
    this.str = '我终于改名字啦';
    this.changeEV.emit(this.str);
    this.cs.emit(this.str);
  }


}
